import { createSlice } from '@reduxjs/toolkit'
import { RootState } from './store'

const initialState = {
	English: [
		{ word: 'hello', def: '你好', remembered: true },
		{ word: 'apple', def: '苹果', remembered: false },
		{ word: 'name', def: '名字', remembered: false }
	],
	Spanish: [
		{ word: 'hola', def: '你好', remembered: false },
		{ word: 'manzana', def: '苹果', remembered: true },
		{ word: 'nombre', def: '名字', remembered: true }
	]
}

const wordSlice = createSlice({
	name: 'word',
	initialState,
	reducers: {
		addWord: (state, action) => {
			const { language, word, def } = action.payload
			state[language as keyof WordType].push({
				word,
				def,
				remembered: false
			})
		},
		toggleRemembered: (state, action) => {
			const { language, word } = action.payload
			const wordToFind = state[language as keyof WordType].find(w => w.word === word)
			wordToFind!.remembered = !wordToFind?.remembered
		}
	}
})

export type WordType = typeof initialState

export const selectWords = (state: RootState) => {
	const lang = state.settings.selectedLanguage
	return state.word[lang as keyof WordType]
}

export const selectFilteredWords = (state: RootState) => {
	const words = selectWords(state)
	return words
		.filter(word => (state.action.searchTerm ? word.word.startsWith(state.action.searchTerm) : word))
		.filter(word => {
			if (state.action.filter === 'remembered') return word.remembered
			if (state.action.filter === 'unremembered') return !word.remembered
			return true
		})
		.sort((wordA, wordB) => {
			if (state.action.sort === 'asc') return wordA.word.localeCompare(wordB.word)
			if (state.action.sort === 'desc') return wordB.word.localeCompare(wordA.word)
			return 0
		})
}

export const selectRememberedWords = (state: RootState) => {
	return state.word[state.settings.selectedLanguage as keyof WordType].filter(word => word.remembered).length
}

export const selectRemainingWords = (state: RootState) =>
	state.word[state.settings.selectedLanguage as keyof WordType].length - selectRememberedWords(state)

export const { toggleRemembered, addWord } = wordSlice.actions
export const wordReducer = wordSlice.reducer
